package com.geek.video.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.geek.video.enums.ResponseEnum;
import com.geek.video.exception.GlobalException;
import com.geek.video.mapper.AdminDao;
import com.geek.video.domain.Admin;
import com.geek.video.service.AdminService;
import com.geek.video.service.dto.AdminDTO;
import com.geek.video.utils.BeanAndMapTransform;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 管理员表(Admin)表服务实现类
 *
 * @author qinxh
 * @since 2021-01-25 16:33:32
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminDao adminDao;


    @Override
    public AdminDTO queryById(Integer id) {

        if (id == null) {
            throw new GlobalException(ResponseEnum.PARAM_EMPTY);
        }

        Admin admin = this.adminDao.queryById(id);
        AdminDTO dto = new AdminDTO();
        if (admin == null) {
            return dto;
        }
        BeanUtils.copyProperties(admin, dto);
        return dto;
    }

    @Override
    public List<AdminDTO> queryAll(AdminDTO admin) {

        List<Admin> list = adminDao.queryAll(BeanAndMapTransform.bean2Map(admin));

        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(m -> {
            AdminDTO dto = new AdminDTO();
            BeanUtils.copyProperties(m, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public AdminDTO insert(AdminDTO admin) {

        if (admin == null) {
            throw new GlobalException(ResponseEnum.PARAM_EMPTY);
        }

        Admin a = new Admin();
        BeanUtils.copyProperties(admin, a);
        this.adminDao.insert(a);

        admin.setId(a.getId());
        return admin;
    }

    @Override
    public AdminDTO update(AdminDTO admin) {

        if (admin == null || admin.getId() == null) {
            throw new GlobalException(ResponseEnum.PARAM_EMPTY);
        }

        Admin a = new Admin();
        BeanUtils.copyProperties(admin, a);
        this.adminDao.update(a);

        return this.queryById(admin.getId());
    }

    @Override
    public Boolean deleteById(Integer id) {

        return this.adminDao.deleteById(id) > 0;
    }
}